#include "header.h"

SimTable::SimTable()
{
    this->db = NULL;
}

SimTable::SimTable(DBBase *db, const char* tableName)
{
    this->db =db;
    this->tableName = tableName;
    this->simStr = new char[20000];
}

void SimTable::insertItem(int qId, const char *sims)
{
    //构造插入的mysql
    ostringstream os;
    os << "INSERT INTO "<< tableName <<"(qId,sims) VALUES(" << qId << ",\"";
    os << sims << "\")";
    this->db->updateQuery(os.str());
}

const char* SimTable::getSims(int qId)
{
    ostringstream os;
    MYSQL_ROW row;
    os << "SELECT sims from "<< tableName <<" where qId=" << qId;
    MYSQL_RES *result = this->db->query(os.str().c_str());
    while ((row = mysql_fetch_row (result)) != NULL) {
         if (row[0] != NULL) {
             strcpy(this->simStr,row[0]);
         };
    }
    //printf("%lu rows returned\n", (unsigned long)mysql_num_rows(result));
    /*
    if (NULL == result) {
        printf("mysql_store_result() failed\n");
    } else {
        mysqlRow = mysql_fetch_row(mysqlResult);
    }*/
    if(result) {
        mysql_free_result(result);
    }
    return this->simStr;
}

void SimTable::getSimFromDB(vector<mypair> &sim, int qId)
{
    //cout << qId << endl;
    const char *simStr = this->getSims(qId);
    //cout << "**** "<< simStr << endl;
    vector<string> qIds;
    int qNum = 0;
    if (strlen(simStr) > 0) {
        qNum = explode(string(simStr), ",", qIds);
    }
    //cout << qNum << endl;
    vector<string> weightInfo;
    for (int i=0; i< qNum; ++i) {
        weightInfo.clear();
        explode(qIds[i], "@", weightInfo);
        sim.push_back(make_pair(atoi(weightInfo[0].c_str()), atof(weightInfo[1].c_str())));
    }
}
SimTable::~SimTable()
{
    delete simStr;
}
